package org.example.edusmart.controller;

import org.example.edusmart.request.SendCodePojo;
import org.example.edusmart.utils.RedisUtils;
import org.example.edusmart.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class SendCodeController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private JavaMailSender sender;

    /**
     * 发送邮箱验证码
     * @param user
     * @return
     */
    @PostMapping("/SendCode/")
    public Result sendVerificationCode(@RequestBody @Validated SendCodePojo user){
        String email = user.getEmail();
        String jsonStr = email;
        // 生成6位随机数字验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        // 将验证码放入 Redis 中，设置有效时间为 100 分钟
        redisUtils.setValue(jsonStr, code, 100L);
        String subject = "验证码"; // 邮件标题
        String content = "你的验证码如下:" + code + "请尽快输入,验证码将于5分钟之后失效"; //邮件正文
        String from = "1547583188@qq.com"; //发件地址
        // 发送包含验证码的邮件
        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setSubject(subject);
        mail.setText(content);
        mail.setTo(jsonStr);
        mail.setFrom(from);
        sender.send(mail);
        return new Result(code, 200, "发送成功");
    }
}